var express = require('express');
var router = express.Router();


const proCollection = require("../sql/pro");
const sql = require("../sql/sql");
const uuid = require("uuid");
const xlsx = require("node-xlsx");

let pageIndex = 0;
let pageNum = 10;

router.get('/', function(req, res, next) {
  // 获取所有数据

  // 获取分页数据：第一页
  sql.getPageData(proCollection, pageNum, pageIndex).then((data)=>{

    sql.getDataLen(proCollection).then(len=>{
      // 将数据传给页面模板
      res.render("pro",{
        index:0,
        data,
        pageMaxNum: Math.ceil(len/10),
        pageIndex,
        pageNum
      });
    })

  })

});


router.get('/upload', function(req, res, next) {
  let xlsxData = xlsx.parse(__dirname + "/../excel/pro.xlsx")[0].data;
  let arr = [];
  for(let i=1;i<xlsxData.length;i++){
    arr.push({
      proId: "pro-" + uuid.v1(),
      proname: xlsxData[i][1],
      kind: xlsxData[i][2],
      img: xlsxData[i][3],
      beforePri: xlsxData[i][4],
      desc: xlsxData[i][5],
      stock: xlsxData[i][6],
      sales: xlsxData[i][7],
      lastPri: xlsxData[i][8],
      event: xlsxData[i][9]
    });
  }

  sql.addData(proCollection, arr).then(()=>{
    res.redirect("/pro");
  })
});

// 分页
router.get('/page', function(req, res, next) {
  let reqData = req.query;
  // res.send(reqData);
  sql.getPageData(proCollection, 10, reqData.index).then((data)=>{
    sql.getDataLen(proCollection).then(len=>{
      // 将数据传给页面模板
      res.render("pro",{
        index:0,
        data,
        pageMaxNum: Math.ceil(len/10),
        pageIndex:reqData.index,
        pageNum
      });
    })

  })

})

module.exports = router;
